<template>
  <div class="activity-container">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <el-input
          v-model="data.title"
          placeholder="请输入活动标题查询"
          class="search-input"
          :prefix-icon="Search"
      />
      <el-select v-model="data.activityType" placeholder="活动类型" clearable>
        <el-option label="党课" :value="1" />
        <el-option label="团课" :value="2" />
        <el-option label="主题党日" :value="3" />
        <el-option label="志愿服务" :value="4" />
        <el-option label="其他" :value="5" />
      </el-select>
      <el-select v-model="data.status" placeholder="活动状态" clearable>
        <el-option label="未开始" :value="1" />
        <el-option label="进行中" :value="2" />
        <el-option label="已结束" :value="3" />
        <el-option label="已取消" :value="0" />
      </el-select>
      <el-button type="danger" plain @click="load()">查询</el-button>
      <el-button type="danger" plain @click="reset">重置</el-button>
    </div>

    <!-- 数据表格卡片 -->
    <div class="data-card">
      <div class="button-group">
        <el-button type="danger" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增活动
        </el-button>
        <el-button type="danger" plain @click="delBatch">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>

      <el-table :data="data.tableData" stripe max-height="420" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column prop="title" label="活动标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="orgType" label="类型" >
          <template #default="scope">
            <el-tag :type="getOrgTypeTag(scope.row.orgType)">
              {{ getOrgTypeLabel(scope.row.orgType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="activityType" label="活动类型">
          <template #default="scope">
            <el-tag :type="getActivityTypeTag(scope.row.activityType)">
              {{ getActivityTypeLabel(scope.row.activityType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地点" width="120" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.startTime?.substring(0, 16) }}
          </template>
        </el-table-column>
        <el-table-column label="人数" align="center">
          <template #default="scope">
            {{ scope.row.currentParticipants }}/{{ scope.row.maxParticipants }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态"  align="center">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button size="default" type="danger" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>


    <!-- 活动表单对话框 -->
    <el-dialog
        :title="data.form.id ? '编辑活动' : '新增活动'"
        v-model="data.formVisible"
        width="900px"
        destroy-on-close
    >
      <el-form
          :model="data.form"
          :rules="rules"
          ref="activityRef"
          label-width="100px"
          class="two-column-form"
      >
        <div class="form-column">
          <el-form-item label="活动标题" prop="title">
            <el-input v-model="data.form.title" />
          </el-form-item>
          <el-form-item label="活动时间" prop="activityTime">
            <el-date-picker
                v-model="data.form.activityTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <!-- 在活动表单对话框中添加支部选择 -->
          <el-form-item label="所属支部" prop="branchId">
            <el-select
                v-model="data.form.branchId"
                filterable
                placeholder="请选择所属支部"
                clearable
            >
              <el-option
                  v-for="item in data.branchOptions"
                  :key="item.id"
                  :label="item.branchName"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="活动类型" prop="activityType">
            <el-select v-model="data.form.activityType" placeholder="请选择活动类型">
              <el-option label="党课" :value="1" />
              <el-option label="团课" :value="2" />
              <el-option label="主题党日" :value="3" />
              <el-option label="志愿服务" :value="4" />
              <el-option label="其他" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="组织类型" prop="orgType">
            <el-radio-group v-model="data.form.orgType">
              <el-radio :label="2">团组织</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 添加状态选择，仅在编辑时显示 -->
          <el-form-item v-if="data.form.id" label="活动状态" prop="status">
            <el-select v-model="data.form.status" placeholder="请选择活动状态">
              <el-option
                  v-for="(label, value) in statusOptions"
                  :key="value"
                  :label="label"
                  :value="Number(value)"
                  :disabled="isStatusDisabled(Number(value))"
              />
            </el-select>

            <div class="status-tip">
              <el-alert
                  :title="getStatusTip(data.form.status)"
                  type="info"
                  :closable="false"
                  size="small"
              />
            </div>
          </el-form-item>
        </div>

        <div class="form-column">
          <el-form-item label="活动地点" prop="location">
            <el-input v-model="data.form.location" />
          </el-form-item>
          <el-form-item label="报名截止" prop="signupDeadline">
            <el-date-picker
                v-model="data.form.signupDeadline"
                type="datetime"
                placeholder="选择报名截止时间"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="参与人数" prop="maxParticipants">
            <el-input-number v-model="data.form.maxParticipants" :min="1" />
          </el-form-item>
          <el-form-item label="活动内容" prop="content">
            <el-input
                v-model="data.form.content"
                type="textarea"
                :rows="4"
                placeholder="请输入活动内容描述"
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="danger" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import {getUserInfo} from "@/utils/auth";

// 定义响应式数据
const data = reactive({
  title: '',
  activityType: '',
  status: '',
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  multipleSelection: [],
  ids: [],
  user: getUserInfo() || {},
  branchOptions: [],
  currentUser: getUserInfo() || {}
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
  activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  orgType: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  activityTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  signupDeadline: [{ required: true, message: '请选择报名截止时间', trigger: 'change' }],
  maxParticipants: [{ required: true, message: '请输入最大参与人数', trigger: 'blur' }],
  content: [{ required: true, message: '请输入活动内容', trigger: 'blur' }],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ],
  branchId: [{ required: true, message: '请选择所属支部', trigger: 'change' }]
}

// 获取活动类型标签文本
const getActivityTypeLabel = (type) => {
  const types = {
    1: '党课',
    2: '团课',
    3: '主题党日',
    4: '志愿服务',
    5: '其他'
  }
  return types[type] || '未知'
}

// 获取活动类型标签样式
const getActivityTypeTag = (type) => {
  const tags = {
    1: 'danger',
    2: 'warning',
    3: 'success',
    4: 'info',
    5: ''
  }
  return tags[type] || ''
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statuses = {
    0: '已取消',
    1: '未开始',
    2: '进行中',
    3: '已结束'
  }
  return statuses[status] || '未知'
}

// 获取状态标签样式
const getStatusTag = (status) => {
  const tags = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return tags[status] || ''
}
// 获取组织类型标签文本
const getOrgTypeLabel = (type) => {
  const types = {
    2: '团组织'
  }
  return types[type] || '未知'
}

// 获取组织类型标签样式
const getOrgTypeTag = (type) => {
  const tags = {
    1: 'danger',
    2: 'warning'
  }
  return tags[type] || ''
}
const loadBranchOptions = async () => {
  try {
    const res = await request.get('/organizationBranch/getLeaderBranches', {
      params: {
        leaderId: data.currentUser.id,
        orgType: data.form.orgType
      }
    })
    if (res.code === '200') {
      data.branchOptions = res.data
    }
  } catch (error) {
    console.error('加载支部选项失败:', error)
    ElMessage.error('加载支部选项失败')
  }
}
// 加载数据
// 在 load 方法中对返回的数据进行处理
const load = () => {
  request.get('/organizationActivity/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title,
      activityType: data.activityType,
      status: data.status
    }
  }).then(res => {
    if (res.code === '200') {
      // 对数据进行状态检查和更新
      data.tableData = res.data.list;
      data.total = res.data?.total;
      console.log(res.data)
    } else {
      ElMessage.error(res.msg);
    }
  })
}


// 新增按钮点击
const handleAdd = () => {
  data.form = {
    orgType: data.currentUser.userType === 1 ? 1 : 2,
    status: 1,
    currentParticipants: 0,
    creatorId: data.currentUser.id
  }
  loadBranchOptions()
  data.formVisible = true
}

// 修改组织类型变化的处理
const handleOrgTypeChange = () => {
  data.form.branchId = null
  loadBranchOptions()
}

// 编辑按钮点击
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  loadBranchOptions()
  data.form.activityTime = [row.startTime, row.endTime]
  data.form.creatorId = data.currentUser.id  // 确保设置创建者ID
  data.formVisible = true
}

// 提交表单前的处理
const beforeSubmit = (form) => {
  const processedForm = { ...form }
  if (form.activityTime?.length === 2) {
    processedForm.startTime = form.activityTime[0]
    processedForm.endTime = form.activityTime[1]

    // 如果是新增活动，根据时间自动设置状态
    if (!form.id) {
      const now = new Date()
      const startTime = new Date(processedForm.startTime)
      const endTime = new Date(processedForm.endTime)

      if (now < startTime) {
        processedForm.status = 1 // 未开始
      } else if (now >= startTime && now < endTime) {
        processedForm.status = 2 // 进行中
      } else {
        processedForm.status = 3 // 已结束
      }
    }
  }
  delete processedForm.activityTime
  return processedForm
}
// 保存数据
const save = () => {
  const form = beforeSubmit(data.form)
  const url = form.id ? '/organizationActivity/update' : '/organizationActivity/add'
  const method = form.id ? 'PUT' : 'POST'
  request({
    url,
    method,
    data: form,
    params: {
      leaderId: data.currentUser.id  // 添加 leaderId 参数
    }
  }).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('保存成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 删除单条数据
const del = (id) => {
  ElMessageBox.confirm('确定要删除这条活动记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/organizationActivity/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  ElMessageBox.confirm(`确定要删除这 ${data.ids.length} 条活动记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/organizationActivity/delete/batch', {
      data: data.ids
    }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 表格多选
const handleSelectionChange = (selection) => {
  data.multipleSelection = selection
  data.ids = selection.map(item => item.id)
}

// 重置搜索条件
const reset = () => {
  data.title = ''
  data.activityType = ''
  data.status = ''
  load()
}

// 分页相关方法
const handleSizeChange = (val) => {
  data.pageSize = val
  load()
}

const handleCurrentChange = (val) => {
  data.pageNum = val
  load()
}

// 表单提交
const activityRef = ref()
const submitForm = () => {
  activityRef.value.validate((valid) => {
    if (valid) {
      save()
    } else {
      ElMessage.error('请填写必填项')
      return false
    }
  })
}
// 状态选项
const statusOptions = {
  0: '已取消',
  1: '未开始',
  2: '进行中',
  3: '已结束'
}

// 判断状态是否应该被禁用
// 判断状态是否应该被禁用
const isStatusDisabled = (status) => {
  if (!data.form.id) return false

  const now = new Date()
  const startTime = new Date(data.form.startTime)
  const endTime = new Date(data.form.endTime)

  // 当前活动状态
  const currentStatus = data.form.status

  // 已结束(3)或已取消(0)的活动不能改变状态
  if (currentStatus === 3 || currentStatus === 0) {
    return true
  }

  // 未开始的活动（status === 1）
  if (currentStatus === 1) {
    // 只能改为已取消
    return status !== 0
  }

  // 进行中的活动（status === 2）
  if (currentStatus === 2) {
    // 只能改为已取消或已结束
    return ![0, 3].includes(status)
  }

  return false
}

// 添加状态提示信息
const getStatusTip = (status) => {
  const tips = {
    0: '已取消的活动不能更改状态',
    1: '未开始的活动只能取消',
    2: '进行中的活动可以取消或标记为已结束',
    3: '已结束的活动不能更改状态'
  }
  return tips[status] || '请选择活动状态'
}

// 初始加载
load()
loadBranchOptions()
</script>

<style scoped>
/* 容器和卡片基础样式 */
.activity-container {
  padding: 20px;
}

.search-card,
.data-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.search-card {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.data-card {
  overflow-x: auto;
  min-width: 850px;
}

/* 搜索和按钮组件 */
.search-input {
  width: 300px;
}

.button-group {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

/* 表单布局 */
.two-column-form {
  display: flex;
  gap: 20px;
}

.form-column {
  flex: 1;
  min-width: 0;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* Element Plus 主题定制 */
:deep(.el-form-item__content),
:deep(.el-date-picker),
:deep(.el-textarea),
:deep(.el-date-editor.el-input),
:deep(.el-date-editor--datetimerange) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 60px;
}

:deep(.el-table) {
  --el-table-header-bg-color: #fff5f5;
}

:deep(.el-button--danger) {
  --el-button-bg-color: #c8161d;
  --el-button-border-color: #c8161d;
  --el-button-hover-bg-color: #e54b4b;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #c8161d;
  --el-button-active-border-color: #c8161d;
  --el-button-text-color: #fff;
}

:deep(.el-button--danger.is-plain) {
  --el-button-bg-color: #fff;
  --el-button-border-color: #c8161d;
  --el-button-text-color: #c8161d;
  --el-button-hover-text-color: #c8161d;
  --el-button-hover-bg-color: #fff5f5;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #fff5f5;
  --el-button-active-text-color: #c8161d;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #c8161d;
}

/* 按钮动画效果 */
:deep(.el-button) {
  transition: all 0.3s;
}

:deep(.el-button:active) {
  transform: scale(0.98);
}
</style>



